const myAxios = function (config) {
    return new Promise((resolve, reject) => {
        const {method , url ,data,params} = config
        //1.创建一个xhr对象
        const xhr = new XMLHttpRequest()
        if (method.toUpperCase() === 'GET') {
          const str = setParams(params)
         //2.调用open()方法
         xhr.open('GET',params?url +'?'+str:url )
         //4.调用send()方法
         xhr.send()
        } else {
        //2.调用open()方法
        xhr.open('POST',url)
        //3.判断数据类型
        let flag = Object.prototype.toString.call(data) === '[object Object]'
        //4.设置请求头数据格式
        xhr.setRequestHeader('Content-Type',flag?'application/json':'application/x-www-form-urlencoded')
        //5.调用send()方法
        xhr.send(flag?JSON.stringify(data):data)
        }
        //4.监听xhr的状态
        xhr.onreadystatechange = function () {
            if (xhr.readyState ===  4) {
                // console.log(JSON.parse(xhr.responseText));
                if (xhr.status >= 200 && xhr.status<300) {
                    resolve(JSON.parse(xhr.responseText))
                }else {
                    reject('请求失败：'+ xhr.status)
                }
            }
        }    
    })    
}

function setParams(obj) {
    let newArr = []
    for (const k in obj) {
       const str = k+'='+obj[k]
       newArr.push(str)
    }

    return newArr.join('&')
}

